# pip install opencv-python numpy    --lib支持
#  
#   python two_cam_combine.py
import cv2
import numpy as np

def main():
    # 打开两个 UVC 摄像头
    cap1 = cv2.VideoCapture(0)  # 第一个摄像头
    cap2 = cv2.VideoCapture(1)  # 第二个摄像头

    if not cap1.isOpened() or not cap2.isOpened():
        print("Error: Could not open one of the cameras.")
        return

    while True:
        # 读取每个摄像头的帧
        ret1, frame1 = cap1.read()
        ret2, frame2 = cap2.read()

        if not ret1 or not ret2:
            print("Error: Could not read from one of the cameras.")
            break

        # 确保两个帧的大小相同
        height = max(frame1.shape[0], frame2.shape[0])
        width = frame1.shape[1] + frame2.shape[1]

        # 调整帧的大小
        frame1_resized = cv2.resize(frame1, (frame1.shape[1], height))
        frame2_resized = cv2.resize(frame2, (frame2.shape[1], height))

        # 拼接帧
        # 水平拼接 ：np.hstack   垂直拼接 ： np.vstack
        combined_frame = np.hstack((frame1_resized, frame2_resized))

        # 显示拼接后的画面
        cv2.imshow('Combined Frame', combined_frame)

        # 按 'q' 键退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # 释放摄像头和窗口
    cap1.release()
    cap2.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
